﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml;
using System.Xml.Serialization;
using System.Data.Services.Client;
using Social_Photos.Social_Photos_Services;
using System.Xml.Linq;
using System.IO;
using System.Windows.Navigation;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media.Imaging;
using System.Security.Cryptography;
using System.ComponentModel;
using System.Text;
namespace Social_Photos
{
    public partial class TopView : PhoneApplicationPage
    {
        // Set the string of your streaming service implementation.
        static string serviceUriString = UrlConfig.SERVICE_URI_STRING;

        // Declare the service root URI.
        private Uri svcRootUri = new Uri(serviceUriString, UriKind.Absolute);

        // Declare our private binding collection.
        private DataServiceCollection<Photo> _photos;
        private DataServiceCollection<User> _users;
        // Declare the DataServiceContext as private.
        private SocialPhotoModelContainer _context;

       
        NetworkCredential credentials = new NetworkCredential();
        int i = 0;
        public TopView()
        {
            InitializeComponent();
            login.Visibility = System.Windows.Visibility.Visible;

        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.LoadDataTop6();
        }

        // Add Header to Request
        private static void OnSendingRequest(object sender, SendingRequestEventArgs e)
        {
            e.RequestHeaders["User"] = _newUser;
            e.RequestHeaders["Pass"] = _newPass;
        }

        private void LoadDataTop6()
        {
           
            // Display the progress bar.
            this.requestProgress.Visibility = Visibility.Visible;
            this.requestProgress.IsIndeterminate = true;

            // Load data from the data service.
            _context = new SocialPhotoModelContainer(svcRootUri);

            // Call Add Header to Request
            // _context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest);

            _photos = new DataServiceCollection<Photo>(_context);

            // Load the data from the Photo feed.
            _photos.LoadAsync(new Uri(UrlConfig.RANDOM_SERVICE_STRING, UriKind.Relative));

            // Register for the LoadCompleted event to turn off the progress bar and load Thumbnail.
            _photos.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(Photos_LoadCompleted);
        }

        private void Photos_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // Make sure that we load all pages of the Photo feed.
                if (_photos.Continuation != null)
                {
                    // Request the next page from the data service.
                    _photos.LoadNextPartialSetAsync();
                }
                else
                {
                    // Load Thumbnail Photos
                    List<TopPhotosListBox> photoList = new List<TopPhotosListBox>();
                    for (int i = 0; i < _photos.Count; i++)
                    {
                        Photo info = _photos[i];
                        Uri uri = new Uri(UrlConfig.GET_THUMBNAIL+ info.FileName);
                        photoList.Add(new TopPhotosListBox(uri.ToString(), info.FileName, info.Id,
                            info.Likes,info.Dislikes,info.Latitude,info.Longitude));
                    }
                    // Put image
                    PhotosListBox.ItemsSource = photoList;
                }
                this.requestProgress.Visibility = Visibility.Collapsed;
                this.requestProgress.IsIndeterminate = false;
            }
            else
            {
                if (MessageBox.Show(e.Error.Message, "Retry request?",
                    MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    this.LoadDataTop6();
                }
            }
        }

     
        private void login_Click(object sender, RoutedEventArgs e)
        {
            
            if (i == 1) {
              //  NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }else
                cnvLogin.Visibility = System.Windows.Visibility.Visible;
            //login.Visibility = System.Windows.Visibility.Collapsed;
           
        }

        private void login1_Click(object sender, RoutedEventArgs e)
        {
            cnvLogin.Visibility = System.Windows.Visibility.Collapsed;
            i = 1;

            string id = username.Text;
            string pass = passwordBox.Password;
            // Load data from the data service.
            _context = new SocialPhotoModelContainer(svcRootUri);
          
            _users = new DataServiceCollection<User>(_context);
            string para = "username='"+id+"'&password='"+pass+"'";
            // Load the data from the Photo feed.
            _users.LoadAsync(new Uri(UrlConfig.LOGIN_SERVICE_STRING + para, UriKind.Relative));

            // Register for the LoadCompleted event to turn off the progress bar and load Thumbnail.
            _users.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(Users_LoadCompleted);        
            
        }

        private void Users_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            // MessageBox.Show(e.QueryOperationResponse.StatusCode.ToString());
            if (e.Error == null)
            {
                // Make sure that we load all pages of the Photo feed.
                if (_users.Continuation != null)
                {
                    // Request the next page from the data service.
                    _users.LoadNextPartialSetAsync();
                }
                else
                {

                    if (_users.Count > 0)
                    {
                        User info = _users[0];
                        int userID = info.Id;
                        NavigationService.Navigate(new Uri("/MainPage.xaml?userID=" + userID, UriKind.RelativeOrAbsolute));
                    }
                    else
                        MessageBox.Show("Username or Password is Invalid");
                    i = 0;
                }
                this.requestProgress.Visibility = Visibility.Collapsed;
                this.requestProgress.IsIndeterminate = false;
            }
            else
            {
                if (MessageBox.Show(e.Error.Message, "Retry request?",
                    MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    this.LoadDataTop6();
                }
            }
        }

       static string _newUser ="";
       static  string _newPass;
        public SocialPhotoModelContainer Context { get;  set; }
        private void register_Click(object sender, RoutedEventArgs e)
        {
      
            User user = new User();
            string _pass;
            string _rePass;
            _newUser = newUser.Text;
            _newPass = newPass.Password;

            _pass = newPass.Password;
            _rePass = rePass.Password;
            if (_newUser == "" || _newPass == "" || _rePass == "")
            {
                MessageBox.Show("Informations not Null");
                return;
            }
            if (_pass != _rePass)
            {
                MessageBox.Show("Password not map !");
            }
            else
            {
                _context = new SocialPhotoModelContainer(svcRootUri);

            // Call Add Header to Request
             _context.SendingRequest += new EventHandler<SendingRequestEventArgs>(OnSendingRequest);
                _users = new DataServiceCollection<User>(_context);

            // Load the data from the Photo feed.
                _users.LoadAsync(new Uri(UrlConfig.SIGN_UP, UriKind.Relative));

            // Register for the LoadCompleted event to turn off the progress bar and load Thumbnail.
                _users.LoadCompleted += new EventHandler<LoadCompletedEventArgs>(Users2_LoadCompleted);
            }
        }
        private void Users2_LoadCompleted(object sender, LoadCompletedEventArgs e)
        {
            // MessageBox.Show(e.QueryOperationResponse.StatusCode.ToString());
            if (e.Error == null)
            {
                // Make sure that we load all pages of the Photo feed.
                if (_users.Continuation != null)
                {
                    // Request the next page from the data service.
                    _users.LoadNextPartialSetAsync();
                }
                else
                {

                    if (_users.Count > 0)
                    {
                        MessageBox.Show("Existed Username");                    
                    }
                    i = 0;
                }
                this.requestProgress.Visibility = Visibility.Collapsed;
                this.requestProgress.IsIndeterminate = false;
            }
            else
            {
                MessageBox.Show("Register Successfully !");
                username.Text = _newUser;
                passwordBox.Password = _newPass;
                cnvRegister.Visibility = Visibility.Collapsed;
                cnvLogin.Visibility = Visibility.Visible;

            }
        }



        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            cnvRegister.Visibility = Visibility.Visible;
        }


    }
    public class TopPhotosListBox
    {
        public string image { get; set; }
        public string filename { get; set; }
        public int id { get; set; }
        public short? like { get; set; }
        public short? dislike { get; set; }
        public double? latitude { get; set; }
        public double? longitude { get; set; }
        public TopPhotosListBox(string Image, string FileName, int Id, short? Like, short? Dislike, double? Latitude, double? Longitude)
        {
            this.image = Image;
            this.filename = FileName;
            this.id = Id;
            this.like = Like;
            this.dislike = Dislike;
            this.latitude = Latitude;
            this.longitude = Longitude;
        }

    }

    public class MyPhotoListBox
    {
        public string image { get; set; }
        public string filename { get; set; }
        public int id { get; set; }
        public short? like { get; set; }
        public short? dislike { get; set; }
        public double? latitude { get; set; }
        public double? longitude { get; set; }
        public MyPhotoListBox(string Image, string FileName, int Id, short? Like, short? Dislike, double? Latitude, double? Longitude)
        {
            this.image = Image;
            this.filename = FileName;
            this.id = Id;
            this.like = Like;
            this.dislike = Dislike;
            this.latitude = Latitude;
            this.longitude = Longitude;
        }

    }
}